
package com.yimixian.app.order;

import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.address.ChooseAddressOrStoreActivity;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Order;
import com.yimixian.app.model.User;
import com.yimixian.app.model.ValidatedOrder;
import com.yimixian.app.receiver.ButtonClickTransHelper;
import com.yimixian.app.ui.MessageDialogView;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.NetworkUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfirmOrderActivity extends AbstractOrderActivity implements View.OnClickListener {

    public static final int RESULT_CODE_PAYMENT_STARTED = 10;
    public static final String PAYMENT_METHOD_WECHAT = "WECHAT";
    public static final String PAYMENT_METHOD_ALIPAY = "ALIPAY";
    public static final String PAYMENT_METHOD_BALANCE = "BALANCE";
    public static final String PAYMENT_QQ_WALLET = "QQWALLETPAY";

    @InjectView(R.id.store_address_info_title)
    TextView mStoreAddressInfoTitle;
    @InjectView(R.id.delivery_method_title)
    TextView mDeliveryMethodTitle;
    @InjectView(R.id.address_view)
    AddressViewForConfirmOrder mAddressView;
    @InjectView(R.id.delivery_mode_view)
    DeliveryModelNewView mDeliveryModeView;
    @InjectView(R.id.price_view)
    PricesView mPricesView;
    @InjectView(R.id.order_goods_list_view)
    LinearLayout mOrderGoodsListView;
    @InjectView(R.id.order_free_goods_list_view)
    OrderGoodsListView mFreeOrderGoodsListView;
    @InjectView(R.id.free_goods_title)
    TextView mFreeGoodsTitle;
    @InjectView(R.id.pay_button)
    View mPayButton;
    @InjectView(R.id.fruit_coupon_View)
    FruitCouponView mFruitCouponView;

    private boolean isClearRedPoint = true;
    private CartManager mCartManager;
    private ValidatedOrder mValidatedOrder;
    private int mCurrentDeliveryModeId = -1;
//    private Integer mLastSavedStoreType;

    private Address mAddress;
    // private Store mStore;
    private String mCurrentPayMethodName = "";
    private AppConfig mAppConfig;
    private boolean mIsShowBuyTips;
    private String mConfirmOrderMessage;
    private long duration = -1;
  //  private boolean isSelectFruitCoupon = false;
    private int mBoundId = 0;
    private String mTaskId = "";
    private Handler mHandler = new Handler();
    private long delayTime = 2 * DateUtils.SECOND_IN_MILLIS;
    private int mSelectCoupon = -1;
    private boolean isCreateOrder = true;
    private String remainingBalance="0.00";
    private long groupId;

    private View dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIsPayFinished = true;
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            Intent intent = new Intent(this, UserRegistrationActivity.class);
            startActivityForResult(intent, Constants.USER_REGISTRATION_REQUEST_CODE);
            return;
        }
        DateUtil.setCityUMeng(null, UMengConstants.NEW_ACCOUNT_PV);
        checkAddressId();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void checkAddressId() {
        mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);;
        if (mAddress == null){
            Intent intent = new Intent(this, ChooseAddressOrStoreActivity.class);
            intent.putExtra(ShowAddressesActivity.EXTRA_MODE,
                    ShowAddressesActivity.PICK_ADDRESS_MODE);
            startActivityForResult(intent, Constants.PICK_ADDRESS_REQUEST_CODE);
            return;
        }
        resumeOnCreate(false);

//        mLastSavedStoreType = DataManager.getInstance().get(CacheKeys.LAST_SAVED_STORE_TYPE);
//        if (mLastSavedStoreType == YMXMainActivity.SAVED_STORE_TYPE_ADDRESS
//                && DataManager.getInstance().get(CacheKeys.ADDRESS_ID) == null) {
//            Intent intent = new Intent(this, ChooseAddressOrStoreActivity.class);
//            intent.putExtra(ShowAddressesActivity.EXTRA_MODE,
//                    ShowAddressesActivity.PICK_ADDRESS_MODE);
//            startActivityForResult(intent, Constants.PICK_ADDRESS_REQUEST_CODE);
//            return;
//        }
//        resumeOnCreate(false);
    }

    private void resumeOnCreate(boolean isResume) {
        if (isResume) {
            return;
        }
        setContentView(R.layout.confirm_order_activity);
        ButterKnife.inject(this);
        initView();
        mFruitCouponView.setOnClickListener(this);
        groupId = getIntent().getLongExtra("group_id", 0);
        if (groupId <= 0) {
            finish();
            return;
        }
        if (!mAddress.isPickup) {
            mStoreAddressInfoTitle.setText("配送地址");
            mDeliveryMethodTitle.setText("配送方式和时间");
        } else {
            mStoreAddressInfoTitle.setText("自提点");
            mDeliveryMethodTitle.setText("自提时间");
        }

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

//        if (mLastSavedStoreType == YMXMainActivity.SAVED_STORE_TYPE_ADDRESS) {
//            mStoreAddressInfoTitle.setText("配送地址");
//            mDeliveryMethodTitle.setText("配送方式和时间");
//        } else {
//            mStoreAddressInfoTitle.setText("自提点");
//            mDeliveryMethodTitle.setText("自提时间");
//        }
        mCartManager = CartManager.getInstance();
        mAppConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (mAppConfig != null && !TextUtils.isEmpty(mAppConfig.confirmOrderMessage)) {
            mIsShowBuyTips = true;
            mConfirmOrderMessage = mAppConfig.confirmOrderMessage;
        } else {
            mIsShowBuyTips = false;
        }
        validateOrder();
    }

    private void validateOrder() {
        mProgressDialog = UiUtils.showProgressDialog(this, "创建订单...");
        if (mAddress == null) {
            finish();
            return;
        }
//        if (mLastSavedStoreType == YMXMainActivity.SAVED_STORE_TYPE_ADDRESS &&
//                mDataManager.<Integer> get(CacheKeys.ADDRESS_ID) == null) {
//            finish();
//            return;
//        }

//        (mLastSavedStoreType == YMXMainActivity.SAVED_STORE_TYPE_ADDRESS ?
//                mYmxDataService.validateOrderByAddressId(mCartManager.getGoodsJson(),
//                        mDataManager.<Integer> get(CacheKeys.ADDRESS_ID)) :
//                mYmxDataService.validateOrderByStoreId(mCartManager.getGoodsJson(),
//                        mDataManager.<Integer> get(CacheKeys.STORE_ID)))
        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress == null || mAddress.id == 0) return;
        mYmxDataService.validateOrderByAddressId(groupId,
                mAddress.id).observeOn(
                        AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<ValidatedOrder>() {
                        @Override
                        public void call(ValidatedOrder order) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            mValidatedOrder = order;
                            if (mValidatedOrder == null) {
                                return;
                            }
                            if (mValidatedOrder.getItems() == null
                                || mValidatedOrder.getItems().size() == 0) {
                                showNoEnoughMessage();
                                throw new RuntimeException("果品库存不足");
                            }

                            mBoundId = mValidatedOrder.getBonusId();
                            showOrder();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            if (throwable != null && "果品库存不足".equals(throwable.getMessage())) {
                                return;
                            }
                            UiUtils.toastError(ConfirmOrderActivity.this, throwable);
                            finish();
                        }
                    }
                );

    }

    private void showNoEnoughMessage() {
        final MessageDialogView messageDialogView = new MessageDialogView(ConfirmOrderActivity.this);
        messageDialogView.bind("提示", "订单中的商品已过期或者售空", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ConfirmOrderActivity.this,
                        StatConstants.CONFIRM_ORDER_NO_ENOUGH_CLICK);
                mAllContentFrame.removeView(messageDialogView);
                finish();
            }
        });
        mAllContentFrame.addView(messageDialogView);
    }

    @OnClick({
            R.id.pay_button
    })
    public void onPaymentButtonClicked(final View view) {
        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                UMengConstants.NEW_ACOUNT_PAYBTN);
        if(UiUtils.isFastDoubleClick()) {
            return;
        }
        if (mCurrentDeliveryModeId == -1) {
            if (mAddress == null){
                finish();
                return;
            }
//            final MessageDialogView messageDialogView = new MessageDialogView(this);
//            messageDialogView.bind("提示",
//                mAddress.isPickup ? "请您选择自提时间" : "请您选择配送方式和时间",
//                new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mAllContentFrame.removeView(messageDialogView);
//                    }
//                });
//            UiUtils.setHierarchyChangeListener(mAllContentFrame, this);
//            mAllContentFrame.addView(messageDialogView);
            dialog = UiUtils.showOKDialog(this, mAddress.isPickup ? "请您选择自提时间" : "请您选择配送方式和时间", "确定",  new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UiUtils.hideDialog(dialog);
                }
            });
            return;
        }

        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
            StatConstants.CONFIRM_ORDER_PAY);
        if (mValidatedOrder != null && mValidatedOrder.canPlaceOrder == 0){
            if (!StringUtils.isEmpty(mValidatedOrder.cnpoReason))
                UiUtils.showToast(mValidatedOrder.cnpoReason);
            return;
        }
        if (mIsShowBuyTips) {
            final MessageDialogView messageDialogView = new MessageDialogView(this);
            messageDialogView.bindConfirm("提示", mConfirmOrderMessage, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAllContentFrame.removeView(messageDialogView);
                    mIsShowBuyTips = false;
                    createOrderAndPay();
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAllContentFrame.removeView(messageDialogView);
                }
            });
            UiUtils.setHierarchyChangeListener(mAllContentFrame, this);
            mAllContentFrame.addView(messageDialogView);
            return;
        }
        createOrderAndPay();
    }

    private void createOrderAndPay() {
        if(isCreateOrder) {
            createAsyncOrder();
        } else {
            if(mOrder != null) {
                startPay(mOrder);
            }
        }
    }

    private void startCountDown() {
        mAddressView.setEnabled(false);
        mDeliveryModeView.setEnabled(false);
        mFruitCouponView.setClickable(false);
        mFruitCouponView.setHideBackImage();
        mCountDownTextView.setVisibility(View.VISIBLE);
        if (duration != -1) {
            return;
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//小写的mm表示的是分钟
        Date date = null;
        try {
            date = sdf.parse(mOrder.paymentDueAt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null) return;
        duration = (date.getTime() - System.currentTimeMillis()) / 1000;
        countDownTimerStart(duration);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.USER_REGISTRATION_REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                finish();
                return;
            }
            checkAddressId();
        }

        if (requestCode == Constants.PICK_ADDRESS_REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                finish();
                return;
            }
            resumeOnCreate(false);
        }

        if (requestCode == Constants.CHANGE_ADDRESS_REQUEST_CODE) {
            validateOrder();
        }
        if (Constants.REQUESTCODE_SELECT_COUPON == resultCode) {
            int select = data.getIntExtra(SelectCouponActivity.INTENT_EXTRA_COUPON_SELECT, -1);
            mSelectCoupon = select;
            if (select != -1) {
              //  isSelectFruitCoupon = true;
                mBoundId = mValidatedOrder.getBonus().get(select).getId();
                mFruitCouponView.setFruitCouponSelect(mValidatedOrder.getBonus().get(select));
                reShowOrder();
            } else {
              //  isSelectFruitCoupon = false;
                mBoundId = 0;
                mFruitCouponView.setNoFruitCouponSelect(mValidatedOrder.getBonus());
                reShowOrder();
            }
        }
    }

    private void showOrder() {
        mPayButton.setVisibility(View.VISIBLE);
        mContentFrame.setVisibility(View.VISIBLE);
        if (mAddress == null) return;
        if (!mAddress.isPickup) {
            mAddressView.bind(SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS));
        } else {
            User user = mDataManager.<User> get(CacheKeys.CURRENT_USER);
            if (user != null) {
                mAddressView.bind(SharedPreferencesHelper.getPickUpStoreName(), user.tel);
            }
        }
          addGoodsView();
        
//        if (mValidatedOrder.getFreeItems() != null && mValidatedOrder.getFreeItems().size() > 0) {
//            mFreeGoodsTitle.setVisibility(View.VISIBLE);
//            mFreeOrderGoodsListView.bindFree(mValidatedOrder.getFreeItems());
//        } else {
            mFreeGoodsTitle.setVisibility(View.GONE);
            mFreeOrderGoodsListView.setVisibility(View.GONE);
//        }
            mSelectCoupon=-1;
          if (mValidatedOrder.getBonus()!=null){
            for (int i=0;i<mValidatedOrder.getBonus().size();i++){
                if(mValidatedOrder.getBonus().get(i).getId()==mValidatedOrder.getBonusId()){
                    mSelectCoupon=i;
                }            
            }
          }
           if (mSelectCoupon != -1) {
               //点击优惠券红点后tab红点清除
               if (isClearRedPoint){
                   EventBus.getDefault().post(new OrderListPointTab(0, Constants.RedPointType.BOUNS, true));
                   isClearRedPoint = false;
               }
                mFruitCouponView
                        .setFruitCouponSelect(mValidatedOrder.getBonus().get(mSelectCoupon));
            } else {
                mFruitCouponView.setNoFruitCouponSelect(mValidatedOrder.getBonus());
            }

        //判断当前选择的支付方式时候在返回的支付方式列表中
        if(mValidatedOrder != null && mValidatedOrder.getPaymentMethods() != null) {
            String currentPayMethodName = mCurrentPayMethodName;
            mCurrentPayMethodName = "";
            for (ValidatedOrder.PaymentMethods options : mValidatedOrder.getPaymentMethods()) {
                if(options != null) {
                    if(currentPayMethodName != null && currentPayMethodName.equals(options.getId())) {
                        mCurrentPayMethodName = options.getId();
                        break;
                    }
                }
            }
        }

        ValidatedOrder.DeliveryOptions deliveryOptions = mValidatedOrder.getDeliveryOptions()
                .get(0);
        bindViewByPaymethod(mValidatedOrder.getPaymentMethods());
        bindViewByPrice(mValidatedOrder.getPriceComponents());
//        if (mValidatedOrder.getDeliveryOptions().size() == 1) {
//            mCurrentDeliveryModeId = deliveryOptions.getId();
//        }

        mDeliveryModeView.bind(mValidatedOrder.getDeliveryOptions(),
                mValidatedOrder.getDeliveryOptionId(), new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (view instanceof DeliveryModelNewView) {
                            int deliveryModeId = ((DeliveryModelNewView) view).getDeliveryModeId();
                            if (mCurrentDeliveryModeId == deliveryModeId&&mValidatedOrder.getDeliveryOptions().size()>1) {
                                return;
                            }

                            if (NetworkUtils.isNetworkAvaliable(SystemFramework.getInstance().getGlobalContext())) {
                                mCurrentDeliveryModeId = deliveryModeId;
                            } else {
                                UiUtils.showToast(getString(R.string.errcode_network_unavailable));
                                showOrder();
                                return;
                            }


                            for (ValidatedOrder.DeliveryOptions deliveryOptions : mValidatedOrder
                                    .getDeliveryOptions()) {
                                if (deliveryOptions.getId() == mCurrentDeliveryModeId) {
                                    bindViewByPaymethod(mValidatedOrder.getPaymentMethods());
                                }
                            }
                            reShowOrder();
                        }
                    }
                },ConfirmOrderActivity.this);
    }

    private void bindViewByPrice(List<ValidatedOrder.PriceComponents> priceList) {
        List<ValidatedOrder.PriceComponents> mList = new ArrayList<>();
        for (int i = 0; i < priceList.size(); i++) {
            if (TextUtils.isEmpty(priceList.get(i).getRawName())) {
                mList.add(priceList.get(i));
            } else {
            }
        }

        mPricesView.bindView(mList, mValidatedOrder.getPriceToPay());

    }

    private void bindViewByPaymethod(List<ValidatedOrder.PaymentMethods> payment) {
        User user = mDataManager.get(CacheKeys.CURRENT_USER);
        if (TextUtils.isEmpty(mCurrentPayMethodName)) {
            mCurrentPayMethodName = payment.get(0).getId();
        }
        if (payment == null) {
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < payment.size(); i++) {
            ids.add(payment.get(i).getId());
            map.put(payment.get(i).getId(), payment.get(i).getName());
        }
        if (mAppConfig == null) {
            finish();
            return ;
        }
        mAppConfig.mPaymentMethodTitles = map;
        if(user != null) {
            if (mValidatedOrder!=null&&!TextUtils.isEmpty(mValidatedOrder.remainingBalance)){
                remainingBalance=mValidatedOrder.remainingBalance;
            }
            mPaymentMethodView.bind(ids,remainingBalance + "",
                mAppConfig.mPaymentMethodTitles, mCurrentPayMethodName, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (view instanceof PaymentMethodItemView) {
                            mCurrentPayMethodName = ((PaymentMethodItemView) view)
                                .getPayMethodName();
                        }
                    }
                });
        } else {
            mPaymentMethodView.bind(ids, 0.0 + "",
                mAppConfig.mPaymentMethodTitles, mCurrentPayMethodName, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (view instanceof PaymentMethodItemView) {
                            mCurrentPayMethodName = ((PaymentMethodItemView) view)
                                .getPayMethodName();
                        }
                    }
                });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected String getTitleBarText() {
        return getString(R.string.order_confirm);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fruit_coupon_View:
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_ACCOUNT_CHANGEBOUNSBTN);
                ArrayList<ValidatedOrder.Bonus> list = new ArrayList<>();
                if (mValidatedOrder == null) {
                    return;
                }
                list.addAll(mValidatedOrder.getBonus());
                if (list.size() == 0) {
                    UiUtils.showToast("当前没有优惠券可用!");
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setChecked(false);
                }
                if (mSelectCoupon != -1) {

                    list.get(mSelectCoupon).setChecked(true);
                }
                startActivityForResult(SelectCouponActivity.buildIntent(this, list),
                        Constants.REQUESTCODE_SELECT_COUPON);
                break;

        }
    }

    public void reShowOrder() {
        mProgressDialog = UiUtils.showProgressDialog(this, "创建订单...");

//        (mLastSavedStoreType == YMXMainActivity.SAVED_STORE_TYPE_ADDRESS ?
//                mYmxDataService.validateOrderByAddressId(mCartManager.getGoodsJson(),
//                        mDataManager.<Integer> get(CacheKeys.ADDRESS_ID), mCurrentDeliveryModeId,
//                        mBoundId) :
//                mYmxDataService.validateOrderByStoreId(mCartManager.getGoodsJson(),
//                        mDataManager.<Integer> get(CacheKeys.STORE_ID), mCurrentDeliveryModeId,
//                        mBoundId))
        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress == null || mAddress.id == 0) return;
        mYmxDataService.validateOrderByAddressId(groupId,
                mAddress.id, mCurrentDeliveryModeId,
            mBoundId).observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<ValidatedOrder>() {
                            @Override
                            public void call(ValidatedOrder order) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                // mOrderString = order.getOrderString();
                                if (order == null) {
                                    return;
                                }
                                mValidatedOrder = order;

                                showOrder();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mCurrentDeliveryModeId = -1;
                                showOrder();
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                if (throwable != null && "果品库存不足".equals(throwable.getMessage())) {
                                    return;
                                }
                                UiUtils.toastError(ConfirmOrderActivity.this, throwable);
                                finish();
                            }
                        }
                );

    }

    public void createAsyncOrder() {
        Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
//        if (address==null){
//            return;
//        }
        mProgressDialog = UiUtils.showProgressDialog(this, "创建订单...");
        setPayButtonEnable(false);
        mYmxDataService
                .createAsyncOrder(mValidatedOrder.getOrderString(), address == null ? "" : address.longitude,
                    address == null ? "" : address.latitude).observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<String>() {
                            @Override
                            public void call(String taskId) {
                                mTaskId = taskId;
                                getOrder();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                setPayButtonEnable(true);
                                if (throwable != null && "果品库存不足".equals(throwable.getMessage())) {
                                    return;
                                }
                                UiUtils.toastError(ConfirmOrderActivity.this, throwable);
                                finish();
                            }
                        }
                );

    }

    private void setPayButtonEnable(boolean isEnable) {
        if(mPayButton != null) {
            mPayButton.setEnabled(isEnable);
        }
    }

    public void getOrder() {

        mYmxDataService.createOrder(mTaskId).observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<Order>() {
                            @Override
                            public void call(Order order) {
                                UiUtils.showToast("订单创建完成");
                                if (mProgressDialog != null) {
                                    mProgressDialog.dismiss();
                                }
                                //创建订单完毕后tab订单显示红点
                                EventBus.getDefault().post(new OrderListPointTab(1, Constants.RedPointType.ORDER,
                                        false));
                                startPay(order);
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
//                                mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                if (throwable != null && throwable.getMessage().contains("订单创建中")) {
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            getOrder();
                                        }
                                    }, delayTime);
                                } else {
                                    UiUtils.toastError(ConfirmOrderActivity.this, throwable);
                                }
                            }
                        }
                );

    }

    public void startPay(Order order) {
        if (order == null) {
            return;
        }
        setResult(RESULT_CODE_PAYMENT_STARTED);
        isCreateOrder = false;
        mOrder = order;
        mPaymentId = order.paymentId;
        paymentButtonClicked(mCurrentPayMethodName);
        startCountDown();
        mCartManager.clearCart();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(500);
                if(mHandler != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            setPayButtonEnable(true);
                        }
                    });
                }
            }
        }).start();
        new ButtonClickTransHelper().sendNormalBroadCast(Constants.BROADCAST_RECEIVE_ADDRESS_CHANGE);
    }
    public void addGoodsView(){       
        mOrderGoodsListView.removeAllViews();
        for (int i = 0; i < mValidatedOrder.getItems().size(); i++) {
            final OrderGoodsListView item = new OrderGoodsListView(this);
            item.bindView(mValidatedOrder.getItems().get(i), i, mValidatedOrder.getItems().size());
            mOrderGoodsListView.addView(item, i);
        }
    }

    @Override
    public void onBackPressed() {
        dialog = UiUtils.showOKAndCancelDialog(ConfirmOrderActivity.this, "您真的不要下单尝尝吗？",
                "不考虑啦", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UiUtils.hideDialog(dialog, false);
                        Map<String, String> hashMap = new HashMap<>();
                        hashMap.put("EVENT", "back");
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                UMengConstants.NEW_ACCOUNT_BACK, hashMap);
                        finish();
                    }
                },
                "我再想想", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UiUtils.hideDialog(dialog);
                        Map<String, String> hashMap = new HashMap<>();
                        hashMap.put("EVENT", "cancel");
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                UMengConstants.NEW_ACCOUNT_BACK, hashMap);
                    }
                });
    }
}
